package com.library.service.impl;

import com.library.dao.ReaderDao;
import com.library.entity.Reader;
import com.library.service.ReaderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ReaderServiceImpl implements ReaderService {

    @Autowired
    private ReaderDao readerDao;

    @Override
    @Transactional
    public boolean register(Reader reader) {
        // 检查用户名是否已存在
        Reader existingReader = readerDao.findByUsername(reader.getUsername());
        if (existingReader != null) {
            return false;
        }
        
        // 检查邮箱是否已存在
        existingReader = readerDao.findByEmail(reader.getEmail());
        if (existingReader != null) {
            return false;
        }
        
        return readerDao.insert(reader) > 0;
    }

    @Override
    public Reader login(String username, String password) {
        Reader reader = readerDao.findByUsername(username);
        if (reader != null && reader.getPassword().equals(password)) {
            return reader;
        }
        return null;
    }

    @Override
    public Reader getReaderById(Integer id) {
        return readerDao.findById(id);
    }

    @Override
    public Reader getReaderByUsername(String username) {
        return readerDao.findByUsername(username);
    }

    @Override
    public List<Reader> getAllReaders() {
        return readerDao.findAll();
    }

    @Override
    @Transactional
    public boolean updateReader(Reader reader) {
        return readerDao.update(reader) > 0;
    }

    @Override
    @Transactional
    public boolean changePassword(Integer readerId, String oldPassword, String newPassword) {
        Reader reader = readerDao.findById(readerId);
        if (reader != null && reader.getPassword().equals(oldPassword)) {
            return readerDao.updatePassword(readerId, newPassword) > 0;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean deleteReader(Integer id) {
        return readerDao.delete(id) > 0;
    }
}